<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>采购合同管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/css/public.css" media="all">
    <style>
        .layui-form-pane .layui-form-label {
            width: 120px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 3px 3px 3px 3px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">合同号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="contractNo" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">关联订单号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="relatedOrderNo" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">供应商名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="supplierName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">签约日期</label>
                            <div class="layui-input-inline">
                                <input type="text" name="signDate" id="signDate" autocomplete="off" class="layui-input" placeholder="yyyy-MM-dd">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon">&#xe615;</i> 搜 索
                            </button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-refresh-btn"><i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button id="sumButton" style="float: right; font-size: 16px"
                        class="layui-btn layui-btn-primary layui-btn-sm"><i
                        class="fa fa-arrows-h">执行中合同总金额：</i><span id="sumPrice"></span></button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="show">查看</a>
            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="contractDetail">合同详情</a>
            <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="orderDetail">订单详情</a>
        </script>

    </div>
</div>

<script src="/static/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/static/lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
<script src="/static/js/common.js"></script>
<script>
    var lay, form, table, laydate;
    layui.use(['form', 'table', 'laydate'], function () {
        lay = layui.jquery;
        form = layui.form;
        util = layui.util;
        table = layui.table;
        laydate = layui.laydate;

        // 初始化日期选择器
        laydate.render({
            elem: '#signDate',
            type: 'date',
            format: 'yyyy-MM-dd'
        });

        table.render({
            elem: '#currentTableId',
            url: '/purchaseContract/pages',
            toolbar: '#toolbarDemo',
            method: "post",
            request: {
                pageName: "pageNum",
                limitName: "pageSize"
            },
            contentType: "application/json; charset=utf-8",
            where: {
                param: {
                    contractStatus: '70'  // 只显示执行中的合同
                }
            },
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'contractInnerId', width: 120, title: '合同内码', sort: true},
                {field: 'contractNo', width: 100, title: '合同号'},
                {field: 'relatedOrderNo', width: 100, title: '关联订单号'},
                {field: 'supplierName', width: 100, title: '供应商名称'},
                {
                    field: 'signDate',
                    width: 100,
                    title: '签约日期',
                    templet: "<div>{{layui.util.toDateString(d.signDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validStartDate',
                    width: 100,
                    title: '有效起始日期',
                    templet: "<div>{{layui.util.toDateString(d.validStartDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validEndDate',
                    width: 100,
                    title: '有效结束日期',
                    templet: "<div>{{layui.util.toDateString(d.validEndDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'expectedDeliveryDate',
                    width: 100,
                    title: '预计交货日期',
                    templet: "<div>{{layui.util.toDateString(d.expectedDeliveryDate, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'deliveryPlanType', width: 80, title: '交期计划方式'},
                {field: 'paymentTermsType', width: 80, title: '付款期限类型'},
                {field: 'quantity', width: 50, title: '数量'},
                {field: 'unit', width: 50, title: '单位'},
                {field: 'unitPrice', width: 70, title: '单价'},
                {field: 'totalAmount', width: 80, title: '合同总金额'},
                {field: 'contractStatus', width: 60, title: '合同状态', 
                    templet: function(d) {
                        var statusMap = {
                            '10': '准备',
                            '11': '驳回', 
                            '15': '修改',
                            '30': '待审',
                            '70': '执行',
                            '80': '完结',
                            '90': '终止'
                        };
                        return statusMap[d.contractStatus] || d.contractStatus;
                    }
                },
                {field: 'docVersion', width: 50, title: '版本号'},
                {field: 'redFlag', width: 50, title: '红冲标记', 
                    templet: function(d) {
                        return d.redFlag === 'YES' ? '是' : '否';
                    }
                },
                {
                    field: 'createTime',
                    width: 100,
                    title: '创建时间',
                    templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"
                },
                {field: 'createUser', width: 60, title: '创建人'},
                {title: '操作', width: 250, toolbar: '#currentTableBar', align: "center", fixed: 'right'}
            ]],
            done: function (res, curr, count) {
                // 计算总金额
                if ($.common.userIsShowPower()) {
                    let sumPrice = 0;
                    let data = res.data
                    if (data.length > 0) {
                        for (let i in data) {
                            if (data[i].totalAmount) {
                                sumPrice = sumPrice + parseFloat(data[i].totalAmount);
                            }
                        }
                    }
                    $("#sumPrice").html(sumPrice.toFixed(2));
                } else {
                    $('#sumButton').css("display", "none");
                    $("[data-field='totalAmount']").css('display', 'none');
                }
            },
            limits: [5, 10, 15, 20, 25, 50, 100, 500],
            limit: 10,
            page: true
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            search(data);
            return false;
        });

        form.on('submit(data-refresh-btn)', function (data) {
            table.reload('currentTableId');
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'show') {
                // 查看合同基本信息
                showContractInfo(data);
            } else if (obj.event === 'contractDetail') {
                // 合同详情 - 弹窗展示合同模板页面
                showContractDetail(data);
            } else if (obj.event === 'orderDetail') {
                // 订单详情 - 弹窗展示历史订单和当前合同订单
                showOrderDetail(data);
            }
        });

    });

    function search(data) {
        table.reload('currentTableId', {
            page: {
                curr: 1
            }
            , where: {
                param: data.field
            }
        }, 'data');
    }

    // 查看合同基本信息
    function showContractInfo(data) {
        var content = '<div style="padding: 20px;">';
        content += '<h3>合同基本信息</h3>';
        content += '<table class="layui-table" lay-skin="line">';
        content += '<tr><td width="120">合同号：</td><td>' + (data.contractNo || '') + '</td></tr>';
        content += '<tr><td>关联订单号：</td><td>' + (data.relatedOrderNo || '') + '</td></tr>';
        content += '<tr><td>供应商：</td><td>' + (data.supplierName || '') + '</td></tr>';
        content += '<tr><td>签约日期：</td><td>' + (data.signDate ? layui.util.toDateString(data.signDate, 'yyyy-MM-dd') : '') + '</td></tr>';
        content += '<tr><td>有效起始日期：</td><td>' + (data.validStartDate ? layui.util.toDateString(data.validStartDate, 'yyyy-MM-dd') : '') + '</td></tr>';
        content += '<tr><td>有效结束日期：</td><td>' + (data.validEndDate ? layui.util.toDateString(data.validEndDate, 'yyyy-MM-dd') : '') + '</td></tr>';
        content += '<tr><td>预计交货日期：</td><td>' + (data.expectedDeliveryDate ? layui.util.toDateString(data.expectedDeliveryDate, 'yyyy-MM-dd') : '') + '</td></tr>';
        content += '<tr><td>合同总金额：</td><td>' + (data.totalAmount || '0.00') + '</td></tr>';
        content += '<tr><td>合同状态：</td><td>' + getContractStatusText(data.contractStatus) + '</td></tr>';
        content += '<tr><td>版本号：</td><td>' + (data.docVersion || '') + '</td></tr>';
        content += '</table>';
        content += '</div>';

        layer.open({
            title: '合同信息',
            type: 1,
            area: ['600px', '500px'],
            content: content
        });
    }

    // 合同详情 - 弹窗展示合同模板页面
    function showContractDetail(data) {
        // 简化逻辑：直接传递 contractId，让模板页面自己加载数据
        var index = layer.open({
            title: '合同详情 - ' + data.contractNo,
            type: 2,
            shade: 0.2,
            maxmin: true,
            shadeClose: true,
            area: ['95%', '95%'],
            content: '/static/page1/order1/page3/contractTemplate.html?contractId=' + data.contractInnerId + '&isShow=true',
        });
    }

    // 订单详情 - 弹窗展示历史订单和当前合同订单
    function showOrderDetail(data) {
        var index = layer.open({
            title: '订单详情 - ' + data.relatedOrderNo,
            type: 2,
            shade: 0.2,
            maxmin: true,
            shadeClose: true,
            area: ['90%', '90%'],
            content: '/static/page1/order1/page3/orderHistoryManagement.html?contractId=' + data.contractInnerId + '&relatedOrderNo=' + data.relatedOrderNo,
        });
        lay(window).on("resize", function () {
            layer.full(index);
        });
    }

    // 获取合同状态文本
    function getContractStatusText(status) {
        var statusMap = {
            '10': '准备',
            '11': '驳回', 
            '15': '修改',
            '30': '待审',
            '70': '执行',
            '80': '完结',
            '90': '终止'
        };
        return statusMap[status] || status;
    }
</script>

</body>
</html>
